package com.wanyangproject.popuwindow;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.utils.WXTextObject;
import cn.sharesdk.wechat.utils.WXWebpageObject;

import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wanyangproject.R;
import com.wanyangproject.activity.LoginActivity;
import com.wanyangproject.activity.TieZiXiangQingActivity;
import com.wanyangproject.base.MyApp;
import com.wanyangproject.entity.ChuanZhiEntity;
import com.wanyangproject.entity.ZhaoPinFenXiangEntity;
import com.wanyangproject.utils.ShareUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

/**
 * Created by 甜甜 on 2018/8/20.
 */

public class SharePopupWindow extends PopupWindow implements View.OnClickListener {


    private View mView;
    private Context context;
    private TextView tv_weixin_haoyou, tv_qq_haoyou, tv_weixin_pengyouquan, tv_xinlang_weibo, tv_quxiao;
    //分享标题
    private String share_title = "分享测试";
    //分享链接
    private String share_url = "http://www.baidu.com";
    //分享封面图片
    private Bitmap share_img;
    //分享描述
    private String share_desc = "万洋众创城";
    private IWXAPI iwxapi;
    private String image = "http://park.hostop.net/static/wanyang/img/download-logo.png";







//    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo);
//    private ZhaoPinFenXiangEntity.ResponseBean responseBean;


    public SharePopupWindow(Context context, View.OnClickListener itemsOnClick, String title, String url, Bitmap bitmap) {
        super(context);


        this.context = context;
        this.share_title = title;
        this.share_url = url;
        this.share_img = bitmap;
        System.out.println(share_title + "               title");
        System.out.println(share_url + "               url");
        System.out.println(share_img + "               bitmap");
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mView = inflater.inflate(R.layout.share_popuowindow, null);

//        if (android.os.Build.VERSION.SDK_INT > 9) {
//            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//            StrictMode.setThreadPolicy(policy);
//        }

//        responseBean = (ZhaoPinFenXiangEntity.ResponseBean)ChuanZhiEntity.fenxiang;


        tv_weixin_haoyou = mView.findViewById(R.id.tv_weixin_haoyou);
        tv_qq_haoyou = mView.findViewById(R.id.tv_qq_haoyou);
        tv_weixin_pengyouquan = mView.findViewById(R.id.tv_weixin_pengyouquan);
        tv_xinlang_weibo = mView.findViewById(R.id.tv_xinlang_weibo);
        tv_quxiao = mView.findViewById(R.id.tv_quxiao);

        tv_weixin_haoyou.setOnClickListener(this);
        tv_qq_haoyou.setOnClickListener(this);
        tv_weixin_pengyouquan.setOnClickListener(this);
        tv_xinlang_weibo.setOnClickListener(this);
        tv_quxiao.setOnClickListener(this);

        initPopupWindow();
    }



    private void initPopupWindow() {
//        设置PopupWindow的view
        this.setContentView(mView);
//        设置PopupWindow弹出窗体的宽
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
//        设置PopupWindow弹出窗体的宽
        this.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
//        设置PopupWindow弹出窗体可点击
        this.setFocusable(true);
//        设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.Animation);
//        点击外部popueWindow消失
//        this.setOutsideTouchable(true);
//        实例化一个ColorDrawable颜色为半透明
        ColorDrawable colorDrawable = new ColorDrawable(0xb0000000);
//        设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(colorDrawable);
//        mView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                int height = mView.findViewById(R.id.linearLayout_share).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
    }


    private boolean isWebchatAvaliable() {
        //检测手机上是否安装了微信
         try {
        context.getPackageManager().getPackageInfo("com.tencent.mm", PackageManager.GET_ACTIVITIES);
        return true;
    } catch(Exception e)

    {
        return false;
    }

}


    @Override
    public void onClick(View view) {
        switch (view.getId()){
//            微信好友
            case R.id.tv_weixin_haoyou:
//                if (!LoginActivity.iwxapi.isWXAppInstalled()) {
//                    Toast.makeText(context, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
//                    return;
//                }



                com.tencent.mm.opensdk.modelmsg.WXWebpageObject webpage = new com.tencent.mm.opensdk.modelmsg.WXWebpageObject();
                webpage.webpageUrl = share_url;

                WXMediaMessage msg = new WXMediaMessage(webpage);

                msg.title = share_title;
                msg.description = share_desc;

//                Bitmap bitmap = BitmapFactory.decodeFile(share_img);
                msg.setThumbImage(share_img);


                SendMessageToWX.Req req = new SendMessageToWX.Req();
//             WXSceneTimeline朋友圈    WXSceneSession聊天界面
                req.scene = SendMessageToWX.Req.WXSceneSession;//聊天界面
                req.message = msg;
                req.transaction = String.valueOf(System.currentTimeMillis());
                LoginActivity.iwxapi.sendReq(req);
//                ShareUtils.shareWechat(share_title,share_url,share_desc,share_img,platformActionListener);
                dismiss();
                break;
//            QQ好友
            case R.id.tv_qq_haoyou:
//                Bitmap bitmap1 = BitmapFactory.decodeFile(share_img);

                ShareUtils.shareQQ(share_title,share_url,share_desc,image,platformActionListener);
                dismiss();
                break;
//            微信朋友圈
            case R.id.tv_weixin_pengyouquan:
//                if (!LoginActivity.iwxapi.isWXAppInstalled()) {
//                    Toast.makeText(context, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
//                    return;
//                }



                com.tencent.mm.opensdk.modelmsg.WXWebpageObject webpage1 = new com.tencent.mm.opensdk.modelmsg.WXWebpageObject();
                webpage1.webpageUrl = share_url;

                WXMediaMessage msg1 = new WXMediaMessage(webpage1);

                msg1.title = share_title;
                msg1.description = share_desc;

//                Bitmap bitmap11 = BitmapFactory.decodeFile(share_img);
                msg1.setThumbImage(share_img);

//                msg.thumbData = getWXThumb(bitmap).toByteArray();

                SendMessageToWX.Req req1 = new SendMessageToWX.Req();
//             WXSceneTimeline朋友圈    WXSceneSession聊天界面
                req1.scene = SendMessageToWX.Req.WXSceneTimeline;//聊天界面
                req1.message = msg1;
                req1.transaction = String.valueOf(System.currentTimeMillis());
                LoginActivity.iwxapi.sendReq(req1);




//                ShareUtils.sharepyq(share_title,share_url,share_desc,share_img,platformActionListener);
                dismiss();
                break;
//            新浪微博
            case R.id.tv_xinlang_weibo:
//                Bitmap bitmap111 = BitmapFactory.decodeFile(share_img);
                ShareUtils.shareWeibo(share_title+share_url,share_url,share_desc,share_img,platformActionListener);
                dismiss();
                break;
//            取消按钮
            case R.id.tv_quxiao:
                dismiss();
                break;
        }
    }









//    Bitmap bitmap;
//    public Bitmap returnBitMap(final String url){
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                URL imageurl = null;
//
//                try {
//                    imageurl = new URL(url);
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
//                    conn.setDoInput(true);
//                    conn.connect();
//                    InputStream is = conn.getInputStream();
//                    bitmap = BitmapFactory.decodeStream(is);
//                    is.close();
//                    System.out.println(bitmap+"         bitmap");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//        return bitmap;
//    }
//










//    /*
//       *    get image from network
//       *    @param [String]imageURL
//       *    @return [BitMap]image
//       */
//    public Bitmap returnBitMap(String url){
//        URL myFileUrl = null;
//        Bitmap bitmap = null;
//        try {
//            myFileUrl = new URL(url);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
//        try {
//
//            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
//            conn.setDoInput(true);
//            conn.connect();
//            InputStream is = conn.getInputStream();
//            bitmap = BitmapFactory.decodeStream(is);
//            System.out.println(bitmap+"       bitmap");
//            is.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return bitmap;
//    }








    /**
     * 分享回调
     */
    PlatformActionListener platformActionListener=new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            Toast.makeText(context, "分享成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            Toast.makeText(context, "分享失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(Platform platform, int i) {
            Toast.makeText(context, "分享取消", Toast.LENGTH_SHORT).show();
        }
    };
}
